#!/usr/bin/env python

# Copyright (C) 2010- Peter Bui and Aaron Dingler.
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.

""" SMQ Exchange Binding """

from tempfile import NamedTemporaryFile
from subprocess import call

import os
import sys


def smq_exchange(msg_head, msg_body):
    msg_id = os.path.basename(msg_head[:-5])

    if not os.path.exists(msg_head):
	print >>sys.stderr, 'Message head %s does not exist', msg_head
	sys.exit(1)
    
    if not os.path.exists(msg_body):
	print >>sys.stderr, 'Message body %s does not exist', msg_body
	sys.exit(1)

    header = {}
    try:
	for line in open(msg_head):
	    llist = line.split()
            name  = llist[0]
            value = ' '.join(llist[1:])
	    header[name] = value
    except Exception, e:
	print >>sys.stderr, 'Unable to parse header: %s', str(e)
	sys.exit(1)

    if 'target' not in header:
	print >>sys.stderr, 'Targets not specified in header'
	sys.exit(1)

    if 'relay' not in header:
        header['relay']  = os.environ['SMQ_MANAGER_HOST'] + ':' + os.environ['SMQ_EXCHANGE_QUEUE']
    else:
        header['relay'] += ' ' + os.environ['SMQ_MANAGER_HOST'] + ':' + os.environ['SMQ_EXCHANGE_QUEUE']
    
    targets = header['target'].split()
    if not targets: sys.exit(0)

    log_stream = open(os.path.join(os.environ['SMQ_EXCHANGE_QUEUE'], '.__replay.log'), 'a+')

    for line in log_stream:
        llist = line.split()
        
        if llist[1] == msg_id:
            if llist[0] == 'put':
                try:
                    targets.remove(llist[2])
                except:
                    pass
            elif llist[0] == 'done':
                targets = []

    for target in targets:
        tgt_head = NamedTemporaryFile()

        for n, v in header.iteritems():
            if n == 'target': 
                v = target
            tgt_head.write('%s %s\n' % (n, v))
        tgt_head.flush()

        # TODO: check if target is local
        if os.system('%s/smq_put %s %s %s' % (os.environ['SMQ_MANAGER_BIN_PATH'], target, tgt_head.name, msg_body)) != 0:
            sys.exit(1)

        log_stream.write('put %s %s\n' % (msg_id, os.path.basename(sys.argv[0])))
        log_stream.flush()

    log_stream.write('done %s\n' % (msg_id))
    log_stream.flush()


if __name__ == '__main__':
    if len(sys.argv) == 3:
	smq_exchange(sys.argv[1], sys.argv[2])
    else:
	print >>sys.stderr, 'Use: smq_exchange message_head message_body'

# vim: sts=4 sw=4 ts=8 expandtab ft=python
